//
//  ParkingViewController.m
//  WWXELuShang
//
//  Created by lanou on 15/12/22.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "ParkingViewController.h"
#import "ParkingView.h"
#import "ParkingTimeTableViewCell.h"
#import "SlideView.h"
#import "TimeManage.h"
#import "KeepTimeView.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>

@interface ParkingViewController ()<UIPickerViewDataSource,UIPickerViewDelegate, UITableViewDataSource,UITableViewDelegate,MAMapViewDelegate, AMapSearchDelegate>

@property (nonatomic, weak)TimeManage *timer;

@property (nonatomic, strong)ParkingView *parkView;

@property (nonatomic, strong)SlideView *slideView;

@property (nonatomic, strong)NSMutableArray *timeArray;

@property (nonatomic, strong)KeepTimeView *keepTimeView;

@property (nonatomic, strong)MAMapView *mapView;

@property (nonatomic, strong)AMapSearchAPI *search;



@end

@implementation ParkingViewController



- (void)dealloc {
    [self.timer removeObserver:self forKeyPath:@"nowTime"];
    
}

- (TimeManage *)timer {
    if (!_timer) {
        _timer = [TimeManage sharedTimeManage];
    }
    return _timer;
}

- (NSMutableArray *)timeArray {
    if (!_timeArray) {
        _timeArray = [[NSMutableArray alloc] init];
        for (int i = 0; i < 8; i ++) {
            NSString *str = [NSString stringWithFormat:@"%ld",(NSInteger)i * 30 * 60];
            [_timeArray addObject:str];
        } 
    }
    return _timeArray;
}

- (SlideView *)slideView {
    if (!_slideView) {
        CGRect rectStatus = [[UIApplication sharedApplication] statusBarFrame];
        CGRect rect = self.navigationController.navigationBar.frame;
        NSLog(@"%.1f", rectStatus.size.height);
        CGFloat height = rect.size.height + rectStatus.size.height;
        _slideView = [[SlideView alloc]initWithFrame:CGRectMake(0, kHeight - height, kWidth, kHeight / 5 * 2) target:self];
    }
    
    return _slideView;
}

- (ParkingView *)parkView {
    if (!_parkView) {
        
        _parkView = [[ParkingView alloc] initWithFrame:[UIScreen mainScreen].bounds target:self];
    }
    return _parkView;
    
}

- (KeepTimeView *)keepTimeView {
    if (!_keepTimeView) {
        _keepTimeView = [[KeepTimeView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    }
    return _keepTimeView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [MAMapServices sharedServices].apiKey = @"0e53ec5f2a187e9a7892f660a585c2a6";
    [AMapSearchServices sharedServices].apiKey = @"0e53ec5f2a187e9a7892f660a585c2a6";
    _mapView = [[MAMapView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _mapView.delegate = self;
    _mapView.showsUserLocation = YES;//定位

    
    
    self.title = @"停车计时器";
    [self.view addSubview:self.parkView];
    [self.view addSubview:self.slideView];
    [self.view addSubview:self.keepTimeView];
    self.view.backgroundColor = kBackGroundColor;
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    if ([[defaults valueForKey:@"timer"] isEqualToString:@"isTiming"]) {
        self.parkView.hidden = YES;
    }else {
        self.keepTimeView.hidden = YES;
        
    }
    
        [self.timer.timer fire];
  
    [self.timer addObserver:self forKeyPath:@"nowTime" options:(NSKeyValueObservingOptionNew) context:nil];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self.parkView.timeTableView registerClass:[ParkingTimeTableViewCell class] forCellReuseIdentifier:@"cell"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"smallArrow"] style:(UIBarButtonItemStylePlain) target:self action:@selector(back)];
    
    //停车方法
    [self.slideView.cancelButton addTarget:self action:@selector(willChangeSlideView:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.slideView.sureButton addTarget:self action:@selector(willChangeSlideView:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.parkView.markButton addTarget:self action:@selector(markPlace) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.parkView.parkingButton addTarget:self action:@selector(startReckonByTime) forControlEvents:(UIControlEventTouchUpInside)];
    
    //计时方法
    [self.keepTimeView.stopButton addTarget:self action:@selector(stopReckonByTime) forControlEvents:(UIControlEventTouchUpInside)];
    [self.keepTimeView.showMapButton addTarget:self action:@selector(findCar) forControlEvents:(UIControlEventTouchUpInside)];
    // Do any additional setup after loading the view.
}

- (void)findCar {
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (![[defaults objectForKey:@"findcar"] isEqualToString:@"canFind"]) {
        [self getAlertViewWithMessage:@"没有标记的车位"];
        return;
    }
    
    CLLocation *location = self.mapView.userLocation.location;
    if (location) {
        self.timer.point = CGPointMake(location.coordinate.latitude, location.coordinate.longitude);
        NSLog(@"经度%f",location.coordinate.latitude);
        NSLog(@"纬度%f",location.coordinate.longitude);
        [self changeMap];
        
    }else {
        [self getAlertViewWithMessage:@"定位失败"];
    }
}

- (void)changeMap {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择导航地图" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    UIAlertAction *openMapAction = [UIAlertAction actionWithTitle:@"系统地图" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [self openSystemMap];
    }];
    [alert addAction:cancelAction];
    [alert addAction:openMapAction];
    [self presentViewController:alert animated:YES completion:nil];

}

- (void)openSystemMap {

    //跳转系统地图

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *str = [defaults valueForKey:@"place"];
    CGPoint point = CGPointFromString(str);
    MKMapItem *currentLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc]initWithCoordinate:CLLocationCoordinate2DMake(self.timer.point.x, self.timer.point.y) addressDictionary:nil]] ;
    MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:CLLocationCoordinate2DMake(point.x, point.y) addressDictionary:nil]];
    [MKMapItem openMapsWithItems:@[currentLocation, toLocation]
                   launchOptions:@{MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeWalking,
                                   MKLaunchOptionsShowsTrafficKey: [NSNumber numberWithBool:YES]}];
}


- (void)startReckonByTime {
    
    NSIndexPath *indexPath = [self.parkView.timeTableView indexPathForSelectedRow];
    if (indexPath.row == 0) {
        return;
    }
    if (indexPath.row == 7 && self.timeArray.count <= 8) {
        return;
    }
    if (indexPath.row == 7) {
        self.timer.second = [[self.timeArray lastObject] integerValue];
    }else {
        self.timer.second = [self.timeArray[indexPath.row] integerValue];
    }
    self.timer.isTiming = YES;


    self.keepTimeView.hidden = NO;
    self.parkView.hidden = YES;
    
    NSDate *sendate = [NSDate date];
    
    NSDate *alertDate = [NSDate dateWithTimeInterval:self.timer.second sinceDate:sendate];
    
    
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    [defaults setObject:sendate forKey:@"sendate"];
    
    [defaults setObject:alertDate forKey:@"alertdate"];
    
    [defaults setObject:@"isTiming" forKey:@"timer"];
    
    if (self.timer.isMarked) {
        NSString *str = NSStringFromCGPoint(self.timer.point);
        [defaults setObject:str forKey:@"place"];
    }
    if ([[defaults valueForKey:@"Local"] isEqualToString:@"NO"]) {
        NSLog(@"不进行闹钟提醒");
    }else {
        [self startLocalNotification:self.timer.second];
    }
    
    
}

//闹钟(本地通知)
- (void)startLocalNotification:(NSInteger)time {
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    if (notification != nil) {
        NSDate *nowDate = [NSDate date];
        notification.fireDate = [nowDate dateByAddingTimeInterval:time];
        notification.timeZone = [NSTimeZone defaultTimeZone];//时区
        notification.repeatInterval = 0;//重复次数 枚举值
//        notification.soundName = UILocalNotificationDefaultSoundName;//系统默认声音
        notification.soundName = @"Yinxiao.com.caf";
//        notification.applicationIconBadgeNumber++;//右上角提示数字
        //提示框
        notification.alertBody = @"记录的停车时间到了哦";
        notification.alertAction = @"知道了";
        //设定通知的userInfo,用来标识该通知
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"停车提醒", @"停车提醒", nil];
        notification.userInfo = dic;
        if ([[UIApplication sharedApplication]respondsToSelector:@selector(registerUserNotificationSettings:)]) {
            //如果是IOS8
            UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
            UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];
            [[UIApplication sharedApplication]registerUserNotificationSettings:settings];//注册提醒的类型
        }
        [[UIApplication sharedApplication]scheduleLocalNotification:notification];
        
    }
    
}
//取消提醒
- (void)removeLocationNotification {
    UIApplication *application = [UIApplication sharedApplication];
    NSArray *localNotifications = [[UIApplication sharedApplication]scheduledLocalNotifications];
    for (UILocalNotification *obj in localNotifications) {
        NSString *keyValue = [obj.userInfo objectForKey:@"停车提醒"];
        if ([keyValue isEqualToString:@"停车提醒"]) {
            [application cancelLocalNotification:obj];
        }
    }
    
}




- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"nowTime"]) {
        NSInteger nowSecond = [change[@"new"] integerValue];
        self.keepTimeView.timeLabel.text = [self transformNowTime:nowSecond];
        
        NSInteger time = [TimeManage sharedTimeManage].alertTime;
        
        if (time > 0) {
            
            self.keepTimeView.alertTimeLabel.text =[NSString stringWithFormat:@"距离提醒时间:%@",[self transformNowTime:time]];
        }else {
            self.keepTimeView.alertTimeLabel.text =[NSString stringWithFormat:@"超过提醒时间:%@",[self transformNowTime:-time]];
        }
    }
}


- (void)stopReckonByTime {
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [self removeLocationNotification];
    [defaults setObject:@"endTiming" forKey:@"timer"];
    [defaults setObject:@"cannotFind" forKey:@"findcar"];
    self.timer.isMarked = NO;
    [self.parkView setmarkButtonImage];
    self.keepTimeView.hidden = YES;
    self.parkView.hidden = NO;
}


- (void)markPlace {
    
    [TimeManage sharedTimeManage].isMarked = ![TimeManage sharedTimeManage].isMarked;
    if ([TimeManage sharedTimeManage].isMarked) {
        CLLocation *location = self.mapView.userLocation.location;
        if (location) {
            self.timer.point = CGPointMake(location.coordinate.latitude, location.coordinate.longitude);
             NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:@"canFind" forKey:@"findcar"];
            NSLog(@"经度%f",location.coordinate.latitude);
            NSLog(@"纬度%f",location.coordinate.longitude);
            
        }else {
            [self getAlertViewWithMessage:@"定位失败"];
            [TimeManage sharedTimeManage].isMarked = NO;
        }
    }
    [self.parkView setmarkButtonImage];
    
}

- (void)getAlertViewWithMessage:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)willChangeSlideView:(UIButton *)button {
    if (button.tag == 1000) {
        
        NSInteger hourRow = [self.slideView.hourPickerView selectedRowInComponent:0];
        NSInteger minRow = [self.slideView.minutePickerView selectedRowInComponent:0];
        [self.timeArray addObject:[NSString stringWithFormat:@"%ld",hourRow * 60 * 60 + minRow * 60]];
        NSIndexPath *indexPath = [self.parkView.timeTableView indexPathForSelectedRow];
        ParkingTimeTableViewCell *cell = [self.parkView.timeTableView cellForRowAtIndexPath:indexPath];
        cell.timeLabel.text = [NSString stringWithFormat:@"自定义 - %@",[self transformTime:[self.timeArray lastObject]]];
    }
    self.parkView.timeTableView.userInteractionEnabled = YES;
    [self.slideView changeSlideView];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 8;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return kHeight / 16;
}

- (void)back {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ParkingTimeTableViewCell *cell = [self.parkView.timeTableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    if (indexPath.row == 0) {
        cell.timeLabel.text = @"不开启";
    }else if (indexPath.row == 7) {
        cell.timeLabel.text = @"自定义 - 00:00:00";
    }else {   
        cell.timeLabel.text = [self transformTime:self.timeArray[indexPath.row]];
    }
    

    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 7) {
        [self.slideView changeSlideView];
        self.parkView.timeTableView.userInteractionEnabled = NO;
    }
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    
    if ([pickerView isEqual:self.slideView.hourPickerView]) {
        return 24;
    }else {
        return 60;
    }
    
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    
    return [NSString stringWithFormat:@"%.2ld", row];

}

- (NSString *)transformTime:(NSString *)second {
    NSInteger time = [second integerValue];
    NSInteger hour = time / 3600;
    NSInteger mintue = time / 60 % 60;
    return [NSString stringWithFormat:@"%.2ld:%.2ld:00",hour,mintue];
}

- (NSString *)transformNowTime:(NSInteger)nowTime {
    NSInteger hour = nowTime / 3600;
    NSInteger min = nowTime / 60 % 60;
    NSInteger second = nowTime % 60;
    return [NSString stringWithFormat:@"%.2ld:%.2ld:%.2ld",hour,min,second];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
